package com.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import com.dao.UserDAO;
import com.dao.impl.UserDAOImpl;
import com.model.User;

/**
 * Servlet implementation class LoginServlet
 */
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    private Logger logger = Logger.getLogger(LoginServlet.class.getName());
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		// 统一编码
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		
		// 获取页面中输入的信息
		String userName = request.getParameter("userName");
		String passWord = request.getParameter("passWord");
		
		// 查询数据库，判定登录是否成功
		User user = new User();
		user.setUserName(userName);
		user.setPassWord(passWord);
		UserDAO ud = new UserDAOImpl();
		boolean b = ud.loginUser(user);

		String resultJson = null;
		
		if (b) {
			logger.info(user.getUserName()+"成功登录系统");
			// 在跳转之前，把登录对象放置到session中
			// 获取session
			HttpSession session = request.getSession();
			// 往session中添加登录对象
			session.setAttribute("user", user);
			// 成功
			resultJson = "{\"success\":true,\"msg\":\"登陆成功....\"}";
		} else {
			// 失败
			logger.info(user.getUserName()+"登录系统失败");
			resultJson = "{\"success\":false,\"msg\":\"用户名或密码错误!\"}";
		}
		response.getWriter().print(resultJson);
	}

}
